<template>
  <a-modal v-model:visible="visible" :title="title" width="calc(100% - 20px)" :mask-closable="false"
    :modal-style="{ maxWidth: '600px' }" :body-style="{ maxHeight: '70vh' }" @before-ok="save" @close="close">
    <a-form ref="formRef" :model="form" :rules="rules" size="medium" auto-label-width>
      <a-row>
        <a-form-item label="头像" field="avatar">
            <a-upload :action="uploadUrl" :headers="header"   :fileList="file ? [file] : []"
      :show-file-list="false"  @success="handleSuccess"  >
              <template #upload-button>
        <div>
          <div
            class="arco-upload-list-picture custom-upload-avatar"
            v-if="form && form.avatar"
          >
            <img :src="form.avatar" />
            <div class="arco-upload-list-picture-mask">
              <IconEdit />
            </div>
          </div>
          <div v-else class="arco-upload-picture-card" >
            <div class="arco-upload-picture-card-text">
              <IconPlus />
              <div style="margin-top: 10px; font-weight: 600">上传头像</div>
            </div>
          </div>
        </div>
      </template>
            </a-upload>
        </a-form-item>
        <a-col v-bind="col2Props">
          <a-form-item label="用户名" field="username">
            <a-input v-model.trim="form.username" placeholder="请输入用户名" allow-clear :disabled="form.disabled"
              :max-length="10"></a-input>
          </a-form-item>
        </a-col>
        <a-col v-bind="col2Props">
          <a-form-item label="昵称" field="nickname">
            <a-input v-model.trim="form.nickname" placeholder="请输入昵称" allow-clear :max-length="10"></a-input>
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item label="性别" field="gender">
        <a-radio-group v-model="form.gender">
          <a-radio :value="1">男</a-radio>
          <a-radio :value="2">女</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="角色" field="roleIds" :disabled="form.disabled">
        <a-select v-model="form.roleIds" :options="roleOptions" placeholder="请选择所属角色" multiple allow-clear
          :allow-search="{ retainInputValue: true }" />
      </a-form-item>

      <a-form-item label="描述" field="description">
        <a-textarea v-model.trim="form.description" :max-length="200" placeholder="请填写描述" :auto-size="{ minRows: 3 }"
          show-word-limit />
      </a-form-item>

    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import type { ColProps, FormInstance } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { baseAPI } from '@/apis/system/user'
import { useResetReactive } from '@/hooks'
import { useRole } from '@/hooks/app'
import { getToken } from '@/utils/auth'
import * as Regexp from '@/utils/regexp'

const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/file/oss/upload'
const header = computed(() => {
  return {
    "Authorization": getToken() || ''
  }
})
const emit = defineEmits<{
  (e: 'save-success'): void
}>()

 const file = ref();
const { roleList, getRoleList } = useRole()
getRoleList()
const roleOptions = computed(() => roleList.value.map((i) => ({ label: i.name, value: i.roleId })))




const col2Props: ColProps = { xs: 24, sm: 24, md: 12, lg: 12, xl: 12, xxl: 12 }
const formRef = useTemplateRef('formRef')
const userId = ref('')
const isEdit = computed(() => !!userId.value)
const title = computed(() => (isEdit.value ? '编辑用户' : '新增用户'))
const visible = ref(false)

const [form, resetForm] = useResetReactive({
  id: '',
  avatar:'',
  username: '', // 用户名
  nickname: '', // 昵称
  gender: 1 as Gender, // 性别 1男 2女
  roleIds: [] as string[], // 角色(可能多个)
  description: '', // 描述
  disabled: false // 如果 type===1 这为 true, 主要作用是列表复选框禁用状态
})

const rules: FormInstance['rules'] = {
  username: [
    { required: true, message: '请输入用户名' },
    { min: 2, max: 4, message: '长度在 2 - 4个字符' }
  ],
  nickname: [
    { required: true, message: '请输入昵称' },
    { min: 2, max: 4, message: '长度在 2 - 4个字符' }
  ],
  email: [{ match: Regexp.Email, message: '邮箱格式不正确' }],
  phone: [{ match: Regexp.Phone, message: '手机号格式不正确' }],
  deptId: [{ required: true, message: '请选择所属部门' }],
  roleIds: [{ required: true, message: '请选择角色' }],
  status: [{ required: true, message: '请选择状态' }]
}

const handleSuccess = (file) =>{
  const res = file.response
  if(res.code == 200){
    form.avatar = res.data.src
    Message.success('上传成功')

  }else{
    Message.error('上传失败,请重试')

  }
}


const add = () => {
  userId.value = ''
  visible.value = true
}

const edit = async (id: string) => {
  visible.value = true
  userId.value = id
  const res = await baseAPI.getDetail({ id })

  Object.assign(form, res.data)
}

const close = () => {
  formRef.value?.resetFields()
  resetForm()
}

const save = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) return false
    let res = {
      code : 0
    }
    if(form?.id){
      res =  await baseAPI.update(form)
 
    }else{
      res =  await baseAPI.add(form)


    }

    if (res.code == 200) {
      if(!form?.id){
        Message.success('保存成功， 默认密码 123456')
      }else{
        Message.success('修改成功')
      }
      emit('save-success')
      return true
    } else {
      return false
    }
  } catch {
    return false
  }
}

defineExpose({ add, edit })
</script>
